package com.mingqijia.gassafety.job.service.mbp;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gap.basic.exception.BizException;
import com.gap.cache.redis.RedisCache;
import com.mingqijia.gassafety.db.entity.Dictionary;
import com.mingqijia.gassafety.job.service.DictionaryService;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.constant.MbpConst;
import com.mingqijia.gassafety.shared.utils.HttpUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import lombok.extern.slf4j.Slf4j;

/**
 * @version 1.0.0
 * @Author: duanhongxiang
 * @Date: 2024/3/25 16:47
 */
@Component
@Slf4j
public class MbpService {
    @Value(value = "${newtcis.api.server}")
    public String serverUrl;

    @Value(value = "${newtcis.api.clientId}")
    public String clientId;

    @Value(value = "${newtcis.api.clientSecret}")
    public String clientSecret;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    RedisCache redisCache;

    /**
     * 获取mbp服务器的请求地址
     * @param spId
     * @return
     */
    public String getMbpRequestUrl(String spId){
        String externalUrl = "";
        String redisKey = Constants.SP_MBP_URL+spId;
        externalUrl = redisCache.getCacheStr(redisKey);
        if( StringUtils.isNotEmpty(externalUrl) ){
            return externalUrl;
        }
        externalUrl = "";
        List<Dictionary> dictionarys = dictionaryService.selectDataOrgIdBySpId(spId);
        for (Dictionary dictionary: dictionarys) {
            try {
                String alias = dictionary.getAlias();
                if (StringUtils.isEmpty(alias)) {
                    throw new BizException(spId + "对应的alias为空");
                }

                String[] arr = StringUtils.split(alias,"|");
                if (arr.length < 2) {
                    throw new BizException(alias + "不合法");
                }
                String dataOrgId = arr[0];

                Map<String, Object> params = new HashMap<>();
                params.put("tenantId", dataOrgId);
                String url = serverUrl + "/api/stech-system/fep/manage/detail";
                log.info("NewTcisService——requestUrl：{}", url);
                Map<String, String> headers = new HashMap<>();
                headers.put("Authorization", "Basic " + Base64Utils.encodeToString((clientId + ":" + clientSecret).getBytes()));
                String body = HttpUtil.getBody(JSONObject.toJSONString(params), url, "", headers, 0);
                log.info("NewTcisService——body,响应结果body：{}", body);
                JSONObject jsonObject = JSONObject.parseObject(body);
                if (200 == jsonObject.getInteger("code") && jsonObject.getBoolean("success")) {
                    if (StringUtils.isNotEmpty(externalUrl))
                        externalUrl += ",";
                    externalUrl += jsonObject.getJSONObject("data").getString("externalUrl");
                }
            }catch (Exception e){
               log.error("获取MBP请求地址报错",e);
            }
        }
        if (StringUtils.isNotEmpty(externalUrl)){
            redisCache.setCacheStr(redisKey, externalUrl, 24*60*60,TimeUnit.SECONDS);
        }
        return externalUrl;
    }

    /**
     * 获取安检单的状态
     * @param spId
     * @param params
     * @return
     */
    public Map<String, Object> GetSecurityOrderState(String spId, Map<String, Object> params) {
        String externalUrls = getMbpRequestUrl(spId);
        if (StringUtils.isEmpty(externalUrls)) {
            throw new BizException("MBP externalUrl为空");
        }
        String methodUrl = "/msc/securityRecord/getState";

        String[] externalUrlArr = externalUrls.split(",");

        int code = 1;
        List<Map<String, Object>> lists = new ArrayList<>();
        for (String externalUrl : externalUrlArr) {
            log.info("MbpService——requestUrl：{},参数：{}", externalUrl + methodUrl, JSONObject.toJSONString(params));
            try {
                String respStr = HttpUtil.doPostWithForm(externalUrl, methodUrl, params);
                log.info("MbpService——body,响应结果body：{}", respStr);
                if (StringUtils.isEmpty(respStr)) {
                    continue;
                }
                JSONObject resultObject = JSONObject.parseObject(respStr);
                if (null == resultObject) {
                    continue;
                }
                if (null != resultObject.get("retcode") && 1 == resultObject.getInteger("retcode") &&
                        null != resultObject.get("data")) {//成功
                    JSONArray data = resultObject.getJSONArray("data");
                    code = 0;
                    for (int i = 0; i < data.size(); i++) {
                        Map<String, Object> temp = new HashMap<>();
                        if (1 == data.getJSONObject(i).getInteger("state")) {
                            temp.put("state", MbpConst.WORK_STATE_FINISH);
                        } else {
                            temp.put("state", 0);
                        }
                        temp.put("finishtime", data.getJSONObject(i).getString("securityEndTime"));
                        temp.put("workpkid", data.getJSONObject(i).getString("securityPkid"));
                        lists.add(temp);
                    }
                }
            }catch(Exception e1){
                log.error("MbpService请求报错", e1);
            }
        }  
        Map<String, Object> result = new HashMap<>();
        result.put("code", code);
        result.put("data", lists);
        return result;
    }
}
